<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="TasksForm">
          <a-row>

						<a-col :span="24" style="display: none;">
							<a-form-item label="子合同ID" v-bind="validateInfos.contractsDetailInfoId" id="TasksForm-contractsDetailInfoId" name="contractsDetailInfoId">
								<a-input v-model:value="formData.contractsDetailInfoId" :placeholder="disabled ? '' : '请输入子合同ID'" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="单位名称" v-bind="validateInfos.itemName" id="TasksForm-itemName" name="itemName">
								<a-input v-model:value="formData.itemName" :placeholder="disabled ? '' : '请输入单位名称'" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<a-col :span="24" style="display: none;">
							<a-form-item label="团队ID" v-bind="validateInfos.teamId" id="TasksForm-teamId" name="teamId">
								<a-input v-model:value="formData.teamId" :placeholder="disabled ? '' : '请输入团队ID'" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="团队名" v-bind="validateInfos.teamName" id="TasksForm-teamName" name="teamName">
								<a-input v-model:value="formData.teamName" :placeholder="disabled ? '' : '请输入团队名'" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品类型" v-bind="validateInfos.productType" id="TasksForm-productType" name="productType">
								<a-input v-model:value="formData.productType" :placeholder="disabled ? '' : '请输入产品类型'" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品名称" v-bind="validateInfos.productName" id="TasksForm-productName" name="productName">
								<a-input v-model:value="formData.productName" :placeholder="disabled ? '' : '请输入产品名称'" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>

						<a-col :span="24">
							<a-form-item label="开始时间" v-bind="validateInfos.startTime" id="TasksForm-startTime" name="startTime">
								<a-date-picker :placeholder="disabled ? '' : '请选择开始时间'" v-model:value="formData.startTime" value-format="YYYY-MM-DD" style="width: 100%" :allow-clear="!disabled" :suffix-icon="disabled ? null : undefined" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="结束时间" v-bind="validateInfos.endTime" id="TasksForm-endTime" name="endTime">
								<a-date-picker :placeholder="disabled ? '' : '请选择结束时间'" v-model:value="formData.endTime" value-format="YYYY-MM-DD" style="width: 100%" :allow-clear="!disabled" :suffix-icon="disabled ? null : undefined" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="任务状态" v-bind="validateInfos.taskStatus" id="TasksForm-taskStatus" name="taskStatus">
								<a-select v-model:value="formData.taskStatus" :placeholder="disabled ? '' : '请选择任务状态'" :allow-clear="!disabled" :show-arrow="!disabled">
									<a-select-option value="未完成">未完成</a-select-option>
									<a-select-option value="已完成">已完成</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>

          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../Tasks.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    contractsDetailInfoId: '',
    itemName: '',
    teamId: '',
    teamName: '',
    productType: '',
    productName: '',
    taskStatus: '未完成',
    startTime: '',
    endTime: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      // 处理数据库字段名映射
      if (record.contracts_detail_info_id) {
        tmpData.contractsDetailInfoId = record.contracts_detail_info_id;
      }
      if (record.item_name) {
        tmpData.itemName = record.item_name;
      }
      if (record.team_id) {
        tmpData.teamId = record.team_id;
      }
      if (record.team_name) {
        tmpData.teamName = record.team_name;
      }
      if (record.product_type) {
        tmpData.productType = record.product_type;
      }
      if (record.product_name) {
        tmpData.productName = record.product_name;
      }
      if (record.task_status) {
        tmpData.taskStatus = record.task_status;
      }
      if (record.start_time) {
        tmpData.startTime = record.start_time;
      }
      if (record.end_time) {
        tmpData.endTime = record.end_time;
      }

      //赋值
      Object.assign(formData, tmpData);
      // 【关键修改】如果赋值后状态为空，则设置为默认值
      if (!formData.taskStatus) {
        formData.taskStatus = '未完成';
      }
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch (e: any) {
      if (e && e.errorFields) {
        const firstField = e.errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(e);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
  :deep(.ant-picker-disabled .ant-picker-suffix) {
    display: none;
  }
</style>
